// pages/choose/choose.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    safeTop: '',
    chooseflag: false, // 是否开启选择
    chooseOutUrl: 'https://guinness2024.oss-cn-shanghai.aliyuncs.com/wximgs/radio.png',
    chooseInUrl: 'https://guinness2024.oss-cn-shanghai.aliyuncs.com/wximgs/radio_active.png',
    allPhoto: [],
    userPhotoList: [], // 用户选择的照片
    hiddenScaleBox: true,
    nowImgUrl: '', // 需要放大的图片
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    that.setData({
      safeTop: app.globalData.safeTop
    })

    // 获取照片列表
    let imgs = app.globalData.imgs
    let plist = []
    // 图片处理
    imgs.forEach((item, index) => {
      let info = {
        id: 'p' + index + 1,
        imgurl: item,
        active: false,
        scale: 1,
        x: 0,
        y: 0
      }
      plist.push(info)
    })
    that.setData({
      allPhoto: plist
    })
  },

  // 点击图片放大
  toScale(e) {
    let that = this
    if (!that.data.chooseflag) {
      that.setData({
        hiddenScaleBox: false,
        nowImgUrl: e.currentTarget.dataset.url
      })
    }
  },

  // 关闭放大图片层
  closeScaleBox() {
    let that = this
    that.setData({
      hiddenScaleBox: true
    })
  },

  // 开始选择
  toChoose() {
    let that = this
    that.setData({
      chooseflag: true
    })
  },
  // 选择照片
  chooseImg(e) {
    let id = e.currentTarget.dataset.id
    let that = this
    if (!that.data.chooseflag) {
      return
    }
    that.data.allPhoto.forEach((item) => {
      if (item.id == id && !item.active) {
        that.data.userPhotoList.push(item)
        item.active = true
        that.setData({
          userPhotoList: that.data.userPhotoList,
          allPhoto: that.data.allPhoto
        })

        if (that.data.userPhotoList.length > 3) {
          that.data.userPhotoList.forEach((sitem, sindex) => {
            if (sindex == 0) {
              sitem.active = false
            }
          })
          that.data.userPhotoList.shift()
          that.setData({
            userPhotoList: that.data.userPhotoList,
            allPhoto: that.data.allPhoto
          })
          // console.log(that.data.userPhotoList);
        }
      }
    })
  },
  // 确认选择
  chooseEnd() {
    let that = this
    if (that.data.userPhotoList.length < 3) {
      return wx.showToast({
        title: '请选择3张图片！',
        icon: 'none'
      })
    }
    app.globalData.userPhotoList = that.data.userPhotoList
    wx.redirectTo({
      url: '/pages/preview/preview',
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})